package com.sls.sys.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.page.Pagination;
import com.sls.sys.constant.Constants;
import com.sls.sys.constant.ExceptionCodeDescription;
import com.sls.sys.dao.OperatorDAO;
import com.sls.sys.pojo.OperatorInfo;
import com.sls.sys.pojo.OperatorInfoVO;
import com.sls.sys.querybean.OperatorQuery;
import com.sls.sys.service.OperatorService;

/**
 * 
 * @author wendb
 * 
 */
@Service("operatorService")
public class OperatorServiceImpl implements OperatorService {
	private static Logger log = Logger.getLogger(OperatorServiceImpl.class);

	@Resource(name = "operatorDAO")
	private OperatorDAO operatorDAO;

	private Gson gson = null;

	public OperatorServiceImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public OperatorInfoVO login(String body, Head head) throws Exception {
		OperatorInfoVO op = gson.fromJson(body, OperatorInfoVO.class);
		validate(op);
		String account = op.getAccount();
		String password = op.getPwd();
		if (account == null || password == null) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.LOGIN_ERROR.getCode(),
					ExceptionCodeDescription.LOGIN_ERROR.getDescription());
		}
		OperatorInfoVO operator = this.operatorDAO.queryAllByAccount(account);
		if (operator == null || !password.equals(operator.getPwd())) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.LOGIN_ERROR.getCode(),
					ExceptionCodeDescription.LOGIN_ERROR.getDescription());
		}
		if (Constants.LOCK_OPERATOR.equals(operator.getState())) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.LOCK_OPERATOR.getCode(),
					ExceptionCodeDescription.LOCK_OPERATOR.getDescription());
		}
		List<String> codes = null;
		// 如果是root用户则返回全部权限
		if (operator.getRoot()) {
			codes = operatorDAO.queryAllCodeByAccount(null);
		} else {
			codes = operatorDAO.queryAllCodeByAccount(operator.getRoleId());
		}
		operator.setCodes(gson.toJson(codes));
		op.setLastLoginIp(head.getIp());
		op.setLastLoginDate(new Date());
		this.operatorDAO.updateOperLogin(op);
		log.info("用户：" + operator.getAccount() + "，登录成功.");
		return operator;
	}

	@Override
	public void saveOperatorInfo(String body, Head head) throws Exception {
		OperatorInfoVO op = gson.fromJson(body, OperatorInfoVO.class);
		validateNotEmpty(op);
		if (operatorDAO.queryAllByAccount(op.getAccount()) != null) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_USER_IS_EXIST.getCode(),
					ExceptionCodeDescription.USER_USER_IS_EXIST
							.getDescription());
		}
		op.setId(UUID.randomUUID().toString());
		op.setUpdateAccount(head.getUserId());
		op.setCreateDate(new Date());
		op.setUpdateDate(new Date());
		operatorDAO.insertOperator(op);
	}

	@Override
	public void updateOperatorInfoById(String body, Head head)
			throws Exception {
		OperatorInfoVO op = gson.fromJson(body, OperatorInfoVO.class);
		validate(op);
		if (StringUtils.isEmpty(op.getType())) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_TYPE_IS_EMPTY.getCode(),
					ExceptionCodeDescription.USER_TYPE_IS_EMPTY
							.getDescription());
		}
		if (StringUtils.isEmpty(op.getAccount())) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_ACCOUNT_IS_EMPTY.getCode(),
					ExceptionCodeDescription.USER_ACCOUNT_IS_EMPTY
							.getDescription());
		}
		op.setUpdateAccount(head.getUserId());
		this.operatorDAO.updateOperById(op);
	}

	@Override
	public Pagination<OperatorInfoVO> queryOperators(String body, Head head) throws Exception {
		OperatorQuery query = gson.fromJson(body, OperatorQuery.class);
		validate(query);
		Pagination<OperatorInfoVO> operList = this.operatorDAO
				.queryOperator(query);
		return operList;
	}

	
	@Override
	public OperatorInfoVO queryOperatorInfoByAccount(String body, Head head)
			throws Exception {
		OperatorInfoVO op = gson.fromJson(body, OperatorInfoVO.class);
		validate(op);
		String account = op.getAccount();
		OperatorInfoVO opInfo = operatorDAO.queryAllByAccount(account);
			return opInfo;
	}

	/**
	 * 增加用户时，校验部分字段是否为空
	 * 
	 * @param op
	 * @throws ServerDisponseException
	 */
	private void validateNotEmpty(OperatorInfoVO op)
			throws ServerDisponseException {
		validate(op);
		String account = op.getAccount();
		String password = op.getPwd();
		String state = op.getState();
		String type = op.getType();
		OperatorInfoVO opTemp = this.operatorDAO.queryAllByAccount(account);
		if (StringUtils.isEmpty(account)) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_ACCOUNT_IS_EMPTY.getCode(),
					ExceptionCodeDescription.USER_ACCOUNT_IS_EMPTY
							.getDescription());
		} else if (opTemp != null) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_USER_IS_EXIST.getCode(),
					ExceptionCodeDescription.USER_USER_IS_EXIST
							.getDescription());
		} else if (StringUtils.isEmpty(password)) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_PASSWORD_IS_EMPTY.getCode(),
					ExceptionCodeDescription.USER_PASSWORD_IS_EMPTY
							.getDescription());
		} else if (StringUtils.isEmpty(state)) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_STATE_IS_EMPTY.getCode(),
					ExceptionCodeDescription.USER_STATE_IS_EMPTY
							.getDescription());
		} else if (StringUtils.isEmpty(type)) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_TYPE_IS_EMPTY.getCode(),
					ExceptionCodeDescription.USER_TYPE_IS_EMPTY
							.getDescription());
		} else {
		}
	}

	/**
	 * 校验json字符串生成的对象是否为空，若为空，则说明请求的报文格式不正确
	 * 
	 * @param obj
	 * @throws ServerDisponseException
	 */
	private void validate(Object obj) throws ServerDisponseException {
		if (obj == null) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDescription.PARSE_REQUEST_ERROR
							.getDescription());
		}
	}

	@Override
	public void updatePwdByAccount(String body, Head head) throws Exception {
		OperatorInfoVO operator = gson.fromJson(body, OperatorInfoVO.class);
		OperatorInfoVO o = operatorDAO.queryAllByAccount(operator.getAccount());
		if (o == null || !o.getPwd().equals(operator.getPwd())) {
			throw new ServerDisponseException("88591", "旧密码错误");
		}
		operatorDAO.updatePwdByAccount(operator);
	}

	@Override
	public void checkOperatorAccount(String body, Head head) throws Exception {
		OperatorInfoVO operator = gson.fromJson(body, OperatorInfoVO.class);
		validate(operator);
		operator = operatorDAO.queryAllByAccount(operator.getAccount());
		if (operator != null) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.USER_USER_IS_EXIST.getCode(),
					ExceptionCodeDescription.USER_USER_IS_EXIST
							.getDescription());
		}
	}

	@Override
	public OperatorInfoVO findbasicInfoByAccount(String body, Head head)
			throws Exception {
		OperatorInfoVO operator = gson.fromJson(body, OperatorInfoVO.class);
		validate(operator);
		OperatorInfoVO o = operatorDAO.queryAllByAccount(operator.getAccount());
		return o;
	}

	@Override
	public void update_lockOperator(String body, Head head) throws Exception {
		OperatorInfo operator = gson.fromJson(body, OperatorInfo.class);
		if (operator == null || operator.getId() == null
				|| operator.getState() == null) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDescription.PARSE_REQUEST_ERROR
							.getDescription());
		}
		// 检验状态值的合法性
		if (!(Constants.LOCK_OUT_OPERATOR.equals(operator.getState()) || Constants.LOCK_OPERATOR
				.equals(operator.getState()))) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDescription.PARSE_REQUEST_ERROR
							.getDescription());
		}
		operatorDAO.update_lockOperator(operator);
	}

	@Override
	public OperatorInfoVO queryOperatorById(String body, Head head) throws Exception {
		OperatorInfoVO operator = gson.fromJson(body, OperatorInfoVO.class);
		if (operator == null || operator.getId() == null) {
			throw new ServerDisponseException(
					ExceptionCodeDescription.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDescription.PARSE_REQUEST_ERROR
							.getDescription());
		}
		operator = operatorDAO.queryAllById(operator.getId());
		if (operator != null) {
			operator.setPwd(null);
			return operator;
		}
		return null;

	}

}
